<script lang="ts" setup>
import dayjs from "dayjs"

import { ref, watch } from "vue"

let emigFun = defineEmits(["onTimeSelectionChange"]) //使用defineEmits语法糖的方法来创建自定义事件。

const dDatePicker = ref("")
const selectTxt = ref("week")

//监听dDatePicker
watch(
  () => dDatePicker,
  (newValue) => {
    if (!newValue.value) return
    // let v = [dayjs(newValue.value[0]).unix(), dayjs(newValue.value[1]).unix()]
    let v = {
      start_time: dayjs(newValue.value[0]).format("YYYY-MM-DD HH:mm:ss"),
      end_time: dayjs(newValue.value[1]).format("YYYY-MM-DD HH:mm:ss")
    }
    emigFun("onTimeSelectionChange", v) //左边是自定义事件名，右边数据。
  },
  { deep: true }
)

const selectTime = (p: string) => {
  selectTxt.value = p
  const lastOb = {
    week: 6,
    month: 30
  }
  const end = new Date()
  const start = new Date()
  start.setTime(start.getTime() - 3600 * 1000 * 24 * lastOb[p])
  dDatePicker.value = [start, end]
}

selectTime("week")
</script>

<template>
  <div class="timeRangeSelection">
    <span :class="{ active: selectTxt === 'week', t1: true }" @click="selectTime('week')">本周</span>
    <span :class="{ active: selectTxt === 'month', t1: true }" @click="selectTime('month')">本月</span>
    <el-date-picker
      class="t1"
      v-model="dDatePicker"
      type="daterange"
      start-placeholder="开始时间"
      end-placeholder="结束时间"
      format="YYYY/MM/DD"
    />
  </div>
</template>

<style lang="scss" scoped>
.timeRangeSelection {
  min-width: 350px;
  text-align: end;

  :deep(.el-range-input) {
    line-height: 29px;
    // padding-top: 4px;
  }

  .t1 {
    font-size: 12px;
    font-weight: 400;
    color: var(--el-color-info);
    margin-right: 20px;
    cursor: pointer;
  }

  .active {
    color: #c3181f;
  }
}
</style>
